import 'dart:io';
import 'package:auto_route/auto_route.dart';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/core/utils/toast_utils.dart';
import 'package:casdon/modules/demo/application/notification/demo_camera_notifier.dart';

import 'package:casdon/modules/demo/application/notification/demo_ocr_notifier.dart';
import 'package:casdon/modules/demo/data/api/demo_ocr_api.dart';
import 'package:casdon/modules/demo/data/repository/demo_repository_impl.dart';

import 'package:casdon/modules/recipe/data/model/recipe_placeholder_data.dart';
import 'package:casdon/auto_router.dart';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import 'package:camera/camera.dart';

class DemoOcrSuccess extends ConsumerWidget {
  final String imagePath;
  const DemoOcrSuccess({super.key, required this.imagePath});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final ocrState = ref.read(demoOcrProvider(imagePath));
    final List<RecipeInfo>? recipeList =
        ocrState.ocrResult?.recipeInfoVos ?? [];
    final List<FoodItem>? foodList = ocrState.ocrResult?.foodJsonCallList ?? [];

    return Scaffold(
      backgroundColor: const Color(0xFFF6F6FF),
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        title: const Text("AI食材识别", style: TextStyle(color: Colors.black87)),
        centerTitle: true,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.black87),
          onPressed: () => Navigator.pop(context),
        ),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.only(bottom: 16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            /// 顶部图片和食材统计
            Padding(
              padding: const EdgeInsets.all(16),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  ClipRRect(
                    borderRadius: BorderRadius.circular(12),
                    child: _buildFoodImage(imagePath),
                  ),
                  const SizedBox(width: 12),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        "共识别到 ${foodList!.length} 种食材",
                        style: TextStyle(fontSize: 16.r),
                      ),
                      const SizedBox(height: 4),
                      Text(
                        "结果由AI生成，仅供参考",
                        style: TextStyle(color: Colors.grey, fontSize: 14.r),
                      ),
                    ],
                  ),
                ],
              ),
            ),

            /// 多个食材卡片
            ...foodList.map((food) {
              return _buildFoodSection(food);
            }),

            SizedBox(height: 24.h),

            /// 推荐菜谱
            if (recipeList != null && recipeList.isNotEmpty) ...[
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 16.w),
                child: Text(
                  "根据食材为你推荐菜谱",
                  style: TextStyle(color: Colors.black87, fontSize: 14.r),
                ),
              ),
              const SizedBox(height: 12),
              SizedBox(
                height: 140.h,
                child: ListView.separated(
                  scrollDirection: Axis.horizontal,
                  padding: EdgeInsets.symmetric(horizontal: 16.w),
                  itemBuilder: (context, index) {
                    final recipe = recipeList[index];
                    return GestureDetector(
                      onTap: () {
                        _handelRecipeClick(
                          recipe,
                          context,
                          ocrState.imageUrl ?? "",
                          ref,
                        );
                      },
                      child: _buildRecipeItem(recipe, context),
                    );
                  },
                  separatorBuilder: (_, __) => SizedBox(width: 12.w),
                  itemCount: recipeList.length,
                ),
              ),
            ],

            SizedBox(height: 32.h),

            /// 底部按钮
            Padding(
              padding: const EdgeInsets.symmetric(
                horizontal: 24.0,
                vertical: 8.0,
              ),
              child: Row(
                children: [
                  Expanded(
                    child: _bottomButton(
                      icon: Icons.image_outlined,
                      label: "重新导入",
                      onTap: () async {
                        final pic = await ref
                            .read(cameraControllerProvider.notifier)
                            .pickImage();
                        if (context.mounted == true) {
                          _onImagePicked(pic, context);
                        }
                      },
                    ),
                  ),
                  Expanded(
                    child: _bottomButton(
                      icon: Icons.camera_alt_outlined,
                      label: "重新拍摄",
                      onTap: () {
                        context.router.maybePop();
                      },
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _bottomButton({
    required IconData icon,
    required String label,
    required VoidCallback onTap,
  }) {
    return Container(
      height: 44,
      margin: EdgeInsets.symmetric(horizontal: 8.w),
      child: OutlinedButton.icon(
        onPressed: onTap,
        icon: Icon(icon, color: const Color(0xFF6C63FF)),
        label: Text(
          label,
          style: const TextStyle(color: Color(0xFF6C63FF), fontSize: 14),
        ),
        style: OutlinedButton.styleFrom(
          side: const BorderSide(color: Color(0xFF6C63FF)),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),
      ),
    );
  }

  Widget _buildRecipeImage(RecipeInfo? recipe) {
    if (recipe == null) {
      return SizedBox.shrink();
    }

    if (recipe.isAiRecommend ?? false == true) {
      return Image(
        image: Assets.images.aiRecipeBg.provider(),
        width: 160.w,
        height: 100.h,
        fit: BoxFit.cover,
      );
    }

    String path = recipe.imageUrls ?? recipePlaceHolderImgUrl;
    final isNetwork = path.startsWith('http') || path.startsWith('https');
    final imageProvider = isNetwork
        ? NetworkImage(path.split(",").first)
        : FileImage(File(path)) as ImageProvider;

    return Image(
      image: imageProvider,
      width: 160.w,
      height: 100.h,
      fit: BoxFit.cover,
    );
  }

  Widget _buildFoodImage(String path) {
    final isNetwork = path.startsWith('http') || path.startsWith('https');
    final imageProvider = isNetwork
        ? NetworkImage(path)
        : FileImage(File(path)) as ImageProvider;

    return Image(
      image: imageProvider,
      width: 70.w,
      height: 80.h,
      fit: BoxFit.cover,
    );
  }

  Widget _buildFoodSection(FoodItem food) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),

      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
      ),
      child: Stack(
        children: [
          /// 背景图：右下角
          Positioned(
            right: 0,
            bottom: -15,
            child: Image.asset(
              Assets.images.aiResultBg.path,
              width: 160.w,
              height: 160.w,
              fit: BoxFit.cover,
            ),
          ),

          /// 主体内容
          Container(
            padding: EdgeInsets.all(16.w),
            decoration: BoxDecoration(
              color: Colors.transparent,
              borderRadius: BorderRadius.circular(16),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  food.foodName ?? "未知",
                  style: TextStyle(fontSize: 18.r, fontWeight: FontWeight.bold),
                ),
                SizedBox(height: 16.h),
                Divider(
                  height: 1,
                  thickness: 1,
                  color: Color(0xFFF7F7F7),
                  indent: 16.w,
                  endIndent: 16.w,
                ),
                SizedBox(height: 16.h),
                Text(
                  "每100g营养成分",
                  style: TextStyle(
                    color: Colors.black.withAlpha(60),
                    fontSize: 14.r,
                  ),
                ),
                const SizedBox(height: 8),
                Row(
                  children: [
                    Text(
                      food.nutritionalFacts!.first.name ?? "卡路里",
                      style: TextStyle(
                        color: Color(0xFF6C63FF),
                        fontSize: 14.r,
                      ),
                    ),
                    SizedBox(width: 5.w),
                    Text(
                      "${food.nutritionalFacts!.first.num ?? 0.0}",
                      style: TextStyle(
                        color: Color(0xFF6C63FF),
                        fontWeight: FontWeight.bold,
                        fontSize: 20.r,
                      ),
                    ),
                    SizedBox(width: 5.w),
                    Text(
                      "${food.nutritionalFacts!.first.unit}",
                      style: TextStyle(
                        color: Color(0xFF6C63FF),
                        fontSize: 14.r,
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 28.h),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    for (var group in _chunk(
                      food.nutritionalFacts!.skip(1).toList(),
                      2,
                    ))
                      Padding(
                        padding: const EdgeInsets.only(bottom: 12),
                        child: Row(
                          children: [
                            Expanded(
                              child: Text(
                                "${group[0].name} ${group[0].num} ${group[0].unit}",
                                style: const TextStyle(
                                  color: Colors.black87,
                                  fontSize: 14,
                                ),
                              ),
                            ),
                            if (group.length > 1)
                              Expanded(
                                child: Text(
                                  "${group[1].name} ${group[1].num} ${group[1].unit}",
                                  textAlign: TextAlign.left,
                                  style: const TextStyle(
                                    color: Colors.black87,
                                    fontSize: 14,
                                  ),
                                ),
                              ),
                          ],
                        ),
                      ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildRecipeItem(RecipeInfo recipe, BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Stack(
          children: [
            ClipRRect(
              borderRadius: BorderRadius.circular(12),
              child: _buildRecipeImage(recipe),
            ),

            Positioned(
              right: 4,
              top: 4,
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 2.h),
                decoration: BoxDecoration(
                  color: const Color(0xFF6C63FF),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Text(
                  (recipe.isAiRecommend ?? false) ? "AI推荐" : "智能",
                  style: TextStyle(color: Colors.white, fontSize: 10.r),
                ),
              ),
            ),
          ],
        ),
        SizedBox(height: 8.h),
        Text(
          recipe.recipeName!,
          style: const TextStyle(fontSize: 13, color: Colors.black87),
        ),
      ],
    );
  }

  List<List<T>> _chunk<T>(List<T> list, int size) {
    List<List<T>> chunks = [];
    for (var i = 0; i < list.length; i += size) {
      var end = i + size;
      if (end > list.length) end = list.length;
      chunks.add(list.sublist(i, end));
    }
    return chunks;
  }

  // imageUrl oss的图片地址
  void _handelRecipeClick(
    RecipeInfo recipe,
    BuildContext context,
    String imageUrl,
    WidgetRef ref,
  ) async {
    if (recipe.isAiRecommend ?? false == true) // AI推荐
    {
      if (recipe.recipeName == null || recipe.recipeName!.isEmpty) {
        ToastUtil.show(" recipeName  == null");
        return;
      }

      DemoSseTextRoute(recipe.recipeName!).push(context);
      return;
    } else {
      RecipeDetailRoute(
        recipeId: recipe.id!,
        title: recipe.recipeName!,
        isSmart: true,
      ).push(context);
    }
  }

  Future<void> _onImagePicked(XFile? image, BuildContext context) async {
    if (image == null) {
      ToastUtil.show("拍照失败！");
      return;
    }
    if (!context.mounted) return;
    DemoOcrRoute(image.path).push(context);
  }
}
